package Opgave9_3;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Main {

	public static void main(String[] args) {

		// Create a single person
		Person p = new Person(5, "Ole", "Jensen");
		System.out.println("Created the person: " + p);

		// Test if we can save a person to DB
		try {
			DbDataAccessObject.savePerson(p);
			System.out.println("Saved the person: " + p);
		} catch (SQLException e) {
			e.printStackTrace(); 
			System.out.println("Failed to save person");
			System.exit(1);
		}
		catch(ClassNotFoundException e){

		}

		// Test if we can load a person from DB
		try {
			Person personFromDb = DbDataAccessObject.loadPerson(5);
			System.out.println("Loaded the person: " + personFromDb);
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("Failed to load person");
			System.exit(1);
		}
		catch(ClassNotFoundException e){

		}
	
		executeQuery("select * from Person", new QueryCallBack() {
			public void processRecord(ResultSet rs) throws SQLException {
				System.out.println(rs.getObject(1) + ", " + rs.getObject(2) + ", " + rs.getObject(3));
			}
		});
	}

	private static void executeQuery(String sql, QueryCallBack callback) {
		try {
			Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
		} catch (ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			con = DriverManager.getConnection("jdbc:derby:PersonDB;create=true");
			stmt = con.createStatement();
			rs = stmt.executeQuery(sql);
			while(rs.next()){
			callback.processRecord(rs);
			}
		} catch(SQLException e) {
			System.out.println(e);
			System.out.println("hej");
		} finally {
			con = null;
			stmt = null;
			rs = null;
		}
	}
}
